import { ref, computed, onMounted, h } from "vue";
import { message } from "@/utils/message";
import {
  type TradeAppSettings as TradeAppSettingsOnServer,
  getAllTradeAppSettings,
  createTradeAppSettings,
  updateTradeAppSettings,
  searchCtpSettings
} from "@/api/settings";
import { sendTestEmailCloseStats } from "@/api/notification";
import { isTouchDevice, useBreakpointQuery } from "@/utils/device";
import type { PlusColumn, PlusDialogProps } from "plus-pro-components";
import { ElTag } from "element-plus";
type DialogMode = "new" | "edit" | "copy";

export type TradeAppSettingsClient = {
  name: string;
  ctp_settings_name: string;
  env_vars: { key: string; value: string }[];
  enabled: boolean;
  trade_enabled: boolean;
  app_type: "trade" | "marketdata";
  affinity: string; // keep empty string when not set
  email_enabled: boolean;
  email_addresses: string[]; // array of email addresses
};

const emptyModel = (): TradeAppSettingsClient => ({
  name: "",
  ctp_settings_name: "",
  env_vars: [],
  enabled: true,
  trade_enabled: true,
  app_type: "trade",
  affinity: "",
  email_enabled: false,
  email_addresses: []
});

function toClient(payload: TradeAppSettingsOnServer): TradeAppSettingsClient {
  const emailAddresses =
    payload.email_address && payload.email_address.trim()
      ? payload.email_address
          .split(",")
          .map(addr => addr.trim())
          .filter(Boolean)
      : [];
  return {
    name: payload.name,
    ctp_settings_name: payload.ctp_settings_name,
    enabled: payload.enabled,
    trade_enabled: payload.trade_enabled,
    app_type: payload.app_type,
    affinity: (payload as any).affinity ?? "",
    email_enabled: payload.email_enabled ?? false,
    email_addresses: emailAddresses,
    env_vars: Object.entries(payload.env_vars || {}).map(([key, value]) => ({
      key,
      value: String(value)
    }))
  };
}

function toServer(payload: TradeAppSettingsClient): TradeAppSettingsOnServer {
  const emailAddress =
    payload.email_addresses
      ?.map(addr => addr.trim())
      .filter(Boolean)
      .join(",") || null;
  return {
    name: payload.name,
    ctp_settings_name: payload.ctp_settings_name,
    enabled: payload.enabled,
    trade_enabled: payload.trade_enabled,
    app_type: payload.app_type,
    affinity: (payload.affinity || "").trim(),
    email_enabled: payload.email_enabled,
    email_address: emailAddress,
    env_vars: Object.fromEntries(
      (payload.env_vars || []).map(({ key, value }) => [key, value])
    )
  } as TradeAppSettingsOnServer;
}

export function useTradeAppSettingsPage() {
  const { isMdUp } = useBreakpointQuery();

  // table state
  const tableData = ref<TradeAppSettingsClient[]>([]);
  const searchQuery = ref("");
  const currentRow = ref<TradeAppSettingsClient | null>(null);

  const tableSize = computed(() => (isMdUp() ? "default" : "small"));

  const tableColumns: TableColumnList = [
    {
      label: "配置名称",
      prop: "name",
      sortable: true,
      minWidth: 120,
      showOverflowTooltip: true
    },
    {
      label: "CTP配置",
      prop: "ctp_settings_name",
      sortable: true,
      minWidth: 120,
      showOverflowTooltip: true
    },
    {
      label: "状态",
      prop: "enabled",
      width: 80,
      align: "center",
      filters: [
        { text: "启用", value: "启用" },
        { text: "禁用", value: "禁用" }
      ],
      filterMethod: (value: string, row: TradeAppSettingsClient) => {
        return row.enabled === (value === "启用");
      },
      cellRenderer: ({ row }) =>
        h(
          ElTag,
          {
            type: row.enabled ? "success" : "info"
          },
          () => (row.enabled ? "启用" : "禁用")
        )
    },
    {
      label: "交易",
      prop: "trade_enabled",
      width: 90,
      align: "center",
      filters: [
        { text: "启用", value: "启用" },
        { text: "禁用", value: "禁用" }
      ],
      filterMethod: (value: string, row: TradeAppSettingsClient) => {
        return row.trade_enabled === (value === "启用");
      },
      cellRenderer: ({ row }) =>
        h(
          ElTag,
          {
            type: row.trade_enabled ? "success" : "info"
          },
          () => (row.trade_enabled ? "启用" : "禁用")
        )
    },
    {
      label: "类型",
      prop: "app_type",
      width: 90,
      align: "center",
      sortable: true,
      cellRenderer: ({ row }) =>
        h(
          ElTag,
          {
            type: row.app_type === "trade" ? "primary" : "warning"
          },
          () => (row.app_type === "trade" ? "交易" : "行情")
        )
    },
    { label: "亲和性", prop: "affinity", sortable: true, minWidth: 80 }
  ];

  const filteredData = computed(() => {
    const q = (searchQuery.value || "").toLowerCase();
    if (!q) return tableData.value;
    return tableData.value.filter(row =>
      (row.name || "").toLowerCase().includes(q)
    );
  });

  const isRowSelected = computed(() => !!currentRow.value);

  const onCurrentChange = (row: TradeAppSettingsClient | null) => {
    currentRow.value = row;
  };

  const onRowClick = (row: TradeAppSettingsClient) => {
    if (!isTouchDevice()) return;
    onCurrentChange(row);
    openEdit();
  };

  // dialog state
  const dialogVisible = ref(false);
  const dialogMode = ref<DialogMode>("new");
  const dialogTitle = computed(() => {
    switch (dialogMode.value) {
      case "edit":
        return "编辑配置";
      case "copy":
        return "复制配置";
      default:
        return "新建配置";
    }
  });

  const dialogWidth = computed(() => (isMdUp() ? "720px" : "95vw"));

  const dialogProps = computed<PlusDialogProps>(() => ({
    title: dialogTitle.value,
    width: dialogWidth.value,
    closeOnClickModal: false,
    destroyOnClose: true
  }));

  const formRules = ref<Partial<Record<string, any[]>>>({
    name: [{ required: true, message: "请输入配置名称", trigger: "blur" }],
    ctp_settings_name: [
      { required: true, message: "请选择CTP配置", trigger: "blur" }
    ]
  });

  const fetchCtpSuggestions = async (
    queryString: string,
    cb?: (list: any[]) => void
  ) => {
    const q = (queryString || "").trim();
    if (!q) {
      cb && cb([]);
      return [] as any[];
    }
    try {
      const res = await searchCtpSettings(q);
      const list =
        (res as any).data?.map((x: any) => ({ value: x.name })) || [];
      cb && cb(list);
      return list;
    } catch (e) {
      message(`获取CTP配置建议失败: ${e}`, { type: "error" });
      cb && cb([]);
      return [] as any[];
    }
  };

  const formColumns = ref<PlusColumn[]>([
    { label: "配置名称", prop: "name", colProps: { span: 12 } },
    {
      label: "CTP配置",
      prop: "ctp_settings_name",
      valueType: "autocomplete",
      colProps: { span: 12 },
      fieldProps: {
        // el-autocomplete props
        fetchSuggestions: fetchCtpSuggestions,
        triggerOnFocus: false,
        clearable: true,
        placeholder: "请输入CTP配置名称"
      }
    },
    {
      label: "应用类型",
      prop: "app_type",
      valueType: "select",
      colProps: { span: 12 },
      options: [
        { label: "交易", value: "trade" },
        { label: "行情", value: "marketdata" }
      ]
    },
    { label: "亲和性", prop: "affinity", colProps: { span: 12 } },
    {
      label: "启用状态",
      prop: "enabled",
      valueType: "switch",
      colProps: { span: 8 }
    },
    {
      label: "交易开关",
      prop: "trade_enabled",
      valueType: "switch",
      colProps: { span: 8 }
    },
    {
      label: "邮件通知",
      prop: "email_enabled",
      valueType: "switch",
      colProps: { span: 8 }
    },
    {
      label: "邮件地址",
      prop: "email_addresses",
      colProps: { span: 24 }
    },
    { label: "环境变量", prop: "env_vars", colProps: { span: 24 } }
  ]);

  const dialogModel = ref<TradeAppSettingsClient>(emptyModel());

  const dialogFormProps = computed(() => ({
    columns: formColumns.value,
    rules: formRules.value,
    labelWidth: "100px",
    clearable: true,
    colProps: { span: isMdUp() ? 12 : 24 },
    rowProps: { gutter: 20 }
  }));

  const openNew = () => {
    dialogMode.value = "new";
    dialogModel.value = emptyModel();
    dialogVisible.value = true;
  };

  const openEdit = () => {
    if (!currentRow.value) return;
    dialogMode.value = "edit";
    dialogModel.value = JSON.parse(JSON.stringify(currentRow.value));
    dialogVisible.value = true;
  };

  const openCopy = () => {
    if (!currentRow.value) return;
    dialogMode.value = "copy";
    const copy = JSON.parse(
      JSON.stringify(currentRow.value)
    ) as TradeAppSettingsClient;
    copy.name = "";
    dialogModel.value = copy;
    dialogVisible.value = true;
  };

  const closeDialog = () => {
    dialogVisible.value = false;
  };

  // env var ops for slots
  const addEnvVar = () => {
    dialogModel.value.env_vars.push({ key: "", value: "" });
  };
  const removeEnvVar = (index: number) => {
    dialogModel.value.env_vars.splice(index, 1);
  };

  // email address ops for slots
  const addEmailAddress = () => {
    dialogModel.value.email_addresses.push("");
  };
  const removeEmailAddress = (index: number) => {
    dialogModel.value.email_addresses.splice(index, 1);
  };

  // test send email handler
  const handleTestSendEmail = async () => {
    const emailAddresses =
      dialogModel.value.email_addresses
        ?.map(addr => addr.trim())
        .filter(Boolean) || [];
    const gatewayName = dialogModel.value.ctp_settings_name?.trim();

    if (emailAddresses.length === 0) {
      message("请输入至少一个邮件地址", { type: "warning" });
      return;
    }

    if (!gatewayName) {
      message("请先选择CTP配置", { type: "warning" });
      return;
    }

    try {
      const emailAddressString = emailAddresses.join(",");
      await sendTestEmailCloseStats(gatewayName, emailAddressString);
      message("测试邮件发送成功", { type: "success" });
    } catch (err) {
      message(`测试邮件发送失败: ${err}`, { type: "error" });
    }
  };
  const handleConfirm = async (values: any) => {
    try {
      const payload = values as TradeAppSettingsClient;
      const serverPayload = toServer(payload);
      if (dialogMode.value === "edit") {
        await updateTradeAppSettings(serverPayload);
        message("配置更新成功", { type: "success" });
      } else {
        await createTradeAppSettings(serverPayload);
        message("配置创建成功", { type: "success" });
      }
      closeDialog();
      await fetchAll();
    } catch (err) {
      message(`提交配置失败: ${err}`, { type: "error" });
    }
  };

  const handleConfirmError = () => {
    message("请填写所有必填字段", { type: "warning" });
  };

  const fetchAll = async () => {
    try {
      const res = await getAllTradeAppSettings();
      const list = ((res as any)?.data || []).map(toClient);
      tableData.value = list;
    } catch {
      message("获取交易程序配置失败", { type: "error" });
    }
  };

  onMounted(fetchAll);

  return {
    // header
    searchQuery,
    openNew,
    openEdit,
    openCopy,
    isRowSelected,

    // table
    tableColumns,
    tableSize,
    filteredData,
    onCurrentChange,
    onRowClick,

    // dialog/form
    dialogVisible,
    dialogProps,
    dialogFormProps,
    dialogModel,
    handleConfirm,
    handleConfirmError,
    closeDialog,

    // helpers for slots
    addEnvVar,
    removeEnvVar,
    addEmailAddress,
    removeEmailAddress,

    // test send email
    handleTestSendEmail
  };
}
